/*
 * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.ahoo.wow.spring.boot.starter.prepare

import io.github.oshai.kotlinlogging.KotlinLogging
import me.ahoo.wow.infra.prepare.PrepareKey
import org.springframework.beans.factory.SmartInitializingSingleton
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware

class PrepareKeyInitializer : ApplicationContextAware, SmartInitializingSingleton {
    companion object {
        val log = KotlinLogging.logger { }
    }

    private lateinit var applicationContext: ApplicationContext

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        this.applicationContext = applicationContext
    }

    /**
     * 在所有单例Bean初始化完成后执行
     * 获取所有PrepareKey类型的Bean，由于PrepareKey的初始化工作在构造函数中完成，
     * 所以只要获取到Bean就已完成初始化
     */
    override fun afterSingletonsInstantiated() {
        val prepareKeys = applicationContext.getBeansOfType(PrepareKey::class.java)
        for ((beanName, prepareKey) in prepareKeys) {
            log.info {
                "PrepareKey bean [$beanName] is initialized: $prepareKey"
            }
        }
    }
}
